package com.dwd.hrm.inteceptor;

import com.dwd.hrm.util.HttpUtil;
import com.dwd.hrm.utils.ValidUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class FeignRequestInterceptor implements RequestInterceptor {

    //    private static String TOKEN_URL = "http://localhost:5010/oauth/token?client_id=%s&client_secret=%s&grant_type=client_credentials";
    @Value("${auth.client.tokenurl}")
    private String TOKEN_URL;
    @Value("${auth.client.clientid}")
    private String clientid;
    @Value("${auth.client.secret}")
    private String secret;

    //请求头中的token
    private final String AUTHORIZATION_HEADER = "Authorization";

    /**
     * 创建临时token放到feign请求头
     *
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        //requestTemplate:feign底层用来发请求的http客户端
        //使用客户端模式生成一个临时的Token
        String url = String.format(TOKEN_URL, clientid, secret);
        Map<String, String> tokenMap = HttpUtil.sendPost(url);
        ValidUtils.assertNotNull(tokenMap, "服务调用失败[临时Token获取失败]");

        String token = "Bearer " + tokenMap.get("access_token");
        log.info("Feign拦截器添加请求头：{}", token);
        //3.添加到Feign的请求头
        requestTemplate.header(AUTHORIZATION_HEADER,token);
    }
}
